<script setup lang="tsx">
import { defineExpose, inject, nextTick, ref } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { addRoyiUser, eidtRoyiUser, getRoyiUserMsg } from '@/service/api';

export type OperateType = AntDesign.TableOperateType;
interface Props {
  operateType: OperateType;
  rowData: any;
  deptOptions: any[];
}

interface Emits {
  (e: 'success'): void;
}
const emit = defineEmits<Emits>();

interface Model {
  nickName: any;
  deptId: any;
  phonenumber: any;
  email: any;
  userName: any;
  password: any;
  sex: any;
  status: any;
  postIds: any;
  roleIds: any;
  remark: any;
  workNo: any;
}

const props = defineProps<Props>();
type RuleKey = Extract<keyof Model, 'nickName', 'userName' | 'password' | 'email' | 'phonenumber'>;
const { createRequiredRule, patternRules } = useFormRules();
const rules: Record<RuleKey, App.Global.FormRule> = {
  nickName: createRequiredRule('用户昵称不能为空'),
  userName: createRequiredRule('用户名称不能为空'),
  password: createRequiredRule('用户密码不能为空'),
  email: patternRules.email,
  phonenumber: patternRules.phone
};

const { formRef, validate, resetFields } = useAntdForm();

const model = ref<Model>(getModel());

const replaceFields = {
  children: 'children',
  label: 'label',
  key: 'id',
  value: 'id'
};
function getModel(): Model {
  return {
    nickName: null,
    deptId: null,
    phonenumber: null,
    email: null,
    userName: null,
    password: '123456',
    sex: null,
    status: '0',
    postIds: [],
    roleIds: [],
    remark: null,
    workNo: null
  };
}

const sexList = [
  {
    lable: '男',
    value: '0'
  },
  {
    lable: '女',
    value: '1'
  },
  {
    lable: '未知',
    value: '2'
  }
];

const postOptions = ref<any[]>([]);
const roleOptions = ref<any[]>([]);
const postData = ref(null);
function getPostOptions() {
  // getRoyiUserMsg(props?.rowData?.userId || '').then(({ data, error }) => {
  //   if (!error) {
  //     postOptions.value = data.posts;
  //     roleOptions.value = data.roles;
  //     if (props?.rowData) {
  //       postData.value = data.sysUser;
  //       const { nickName, dept, phonenumber, remark, email, userName, sex, status, workNo } = data.sysUser;
  //       model.value = {
  //         nickName,
  //         deptId: dept.deptId,
  //         phonenumber,
  //         email,
  //         userName,
  //         password: null,
  //         sex,
  //         status,
  //         postIds: data.postIds,
  //         roleIds: data.roleIds,
  //         remark,
  //         workNo
  //       };
  //     }
  //   }
  // });
  getRoyiUserMsg(props?.rowData?.userId || '').then( res => {
    let data = res.otherData
    console.log('data', data)
    postOptions.value = data.posts;
    roleOptions.value = data.roles;
    if (props?.rowData) {
      postData.value = data.data;
      const { nickName, dept, deptId, phonenumber, remark, email, userName, sex, status, workNo } = data.data;
      model.value = {
        nickName,
        // deptId: dept.deptId || null,
        deptId: deptId || null,
        phonenumber,
        email,
        userName,
        password: null,
        sex,
        status,
        postIds: data.postIds || null,
        roleIds: data.roleIds || null,
        remark,
        workNo
      };
    }
  });
}

getPostOptions();

async function sumbitForm() {
  await validate();
  let pro;
  if (props.operateType === 'add') {
    pro = addRoyiUser(model.value);
  } else {
    pro = eidtRoyiUser({ ...model.value, userId: props.rowData.userId });
  }
  const { error } = await pro;
  if (!error) {
    window.$message?.success('操作成功!');
    emit('success');
  }
}

defineExpose({
  sumbitForm
});
</script>

<template>
  <AForm ref="formRef" :model="model" :rules="rules" :label-col="{ lg: 8, xs: 4 }" label-wrap>
    <ARow :gutter="20">
      <ACol :lg="24" :xs="24">
        <AFormItem name="nickName" label="用户昵称" :label-col="{}">
          <AInput v-model:value="model.nickName" placeholder="请输入用户昵称" autocomplete="off" />
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="deptId" label="归属部门" :label-col="{}">
          <!-- <AInput v-model:value="model.nickName" placeholder="请输入归属部门" autocomplete="off" /> -->
          <ATreeSelect
            v-model:value="model.deptId"
            show-search
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择归属部门"
            allow-clear
            tree-default-expand-all
            :tree-data="props.deptOptions"
            :replace-fields="replaceFields"
            tree-node-filter-prop="label"
          >
            <template #title="{ label }">
              {{ label }}
            </template>
          </ATreeSelect>
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="workNo" label="工号" :label-col="{}">
          <AInput v-model:value="model.workNo" placeholder="请输入工号" autocomplete="off" />
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="phonenumber" label="手机号码" :label-col="{}">
          <AInput v-model:value="model.phonenumber" placeholder="请输入手机号码" autocomplete="off" />
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="email" label="邮箱" :label-col="{}">
          <AInput v-model:value="model.email" placeholder="请输入邮箱" autocomplete="off" />
        </AFormItem>
      </ACol>
      <template v-if="!props?.rowData?.userId">
        <ACol :lg="12" :xs="24">
          <AFormItem name="userName" label="用户名" :label-col="{}">
            <AInput v-model:value="model.userName" placeholder="请输入用户名" autocomplete="off" />
          </AFormItem>
        </ACol>
        <ACol :lg="12" :xs="24">
          <AFormItem name="password" label="用户密码" :label-col="{}">
            <AInputPassword v-model:value="model.password" placeholder="请输入用户密码" autocomplete="off" />
          </AFormItem>
        </ACol>
      </template>
      <ACol :lg="12" :xs="24">
        <AFormItem name="sex" label="用户性别" :label-col="{}">
          <ASelect v-model:value="model.sex" placeholder="请选择用户性别">
            <ASelectOption v-for="item in sexList" :key="item.value" :value="item.value">
              {{ item.lable }}
            </ASelectOption>
          </ASelect>
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="status" label="状态" :label-col="{}">
          <ARadioGroup v-model:value="model.status">
            <ARadio value="0">正常</ARadio>
            <ARadio value="1">停用</ARadio>
          </ARadioGroup>
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="postIds" label="岗位" :label-col="{}">
          <ASelect v-model:value="model.postIds" placeholder="请选择岗位" mode="multiple">
            <ASelectOption
              v-for="item in postOptions"
              :key="item.postId"
              :value="item.postId"
              :disabled="item.status == 1"
            >
              {{ item.postName }}
            </ASelectOption>
          </ASelect>
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="roleIds" label="角色" :label-col="{}">
          <ASelect v-model:value="model.roleIds" placeholder="请选择角色" mode="multiple">
            <ASelectOption
              v-for="item in roleOptions"
              :key="item.roleId"
              :value="item.roleId"
              :disabled="item.status == 1"
            >
              {{ item.roleName }}
            </ASelectOption>
          </ASelect>
        </AFormItem>
      </ACol>
      <ACol :lg="24" :xs="24">
        <AFormItem name="remark" label="备注" :label-col="{}">
          <ATextarea v-model:value="model.remark" placeholder="请输入备注" :rows="4" autocomplete="off" />
        </AFormItem>
      </ACol>
    </ARow>
  </AForm>
</template>

<style></style>
